package com.hui.service;

import com.hui.entity.Product;
import com.hui.entity.ProductVo;
import com.hui.entity.ResultMapper;
import com.hui.mapper.ProductMapper;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 李昭辉
 * @Date: 2021/09/26/8:20
 * @Description:
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public void save(Product product) {
        // 保存到数据库
        productMapper.insert(product);
        // 获取新插入id
        Integer id = product.getId();
        // 将id传递给kafka消息队列
        kafkaTemplate.send("product", id.toString());
    }

    @Autowired
    private ElasticsearchTemplate template;

    //    查询条件：name
    //    分页查询：每页5条
    //    排序规则：price，升序
    //    结果过滤：商品价格范围过滤
    //    实现高亮效果
    @Override
    public List<Product> search(ProductVo productVo) {
        // 构建原生查询器
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        // name条件查询
        builder.withQuery(QueryBuilders.matchQuery("name", productVo.getName()));
        // 分页+升序,  注意:从页码0开始
        builder.withPageable(PageRequest.of(productVo.getPageNum() - 1, 5, Sort.by(Sort.Direction.ASC, "price")));
        //  结果过滤：商品价格范围过滤
        RangeQueryBuilder priceRange = QueryBuilders.rangeQuery("price");
        priceRange.gte(productVo.getLowPrice());
        priceRange.lte(productVo.getHighPrice());
        builder.withFilter(priceRange);
        // name字段高亮
        HighlightBuilder.Field field = new HighlightBuilder.Field("name");
        field.preTags("<font style='color:red'>");
        field.postTags("</font>");
        builder.withHighlightFields(field);

        // 查询
        AggregatedPage<Product> result = template.queryForPage(builder.build(), Product.class, new ResultMapper());
        // 获取结果并返回
        return result.getContent();
    }
}
